﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Collections;
using System.Linq;

namespace GoodStuff.Silverlight
{
    /// <summary>
    /// This datagrid will be driven my the meta-model. 
    /// </summary>
    public class AutoDataGrid : DataGrid
    {
        public AutoDataGrid()
        {
            this.AutoGenerateColumns = true;
        }     

        public IEnumerable<string> ColumnNames
        {
            get { return (IEnumerable<string>)GetValue(ColumnNamesProperty); }
            set { SetValue(ColumnNamesProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ColumnNames.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ColumnNamesProperty =
            DependencyProperty.Register("ColumnNames", typeof(IEnumerable<string>), typeof(AutoDataGrid), new PropertyMetadata(new PropertyChangedCallback(OnColumnNamesPropertyChanged)));

        private static void OnColumnNamesPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            AutoDataGrid grid = (AutoDataGrid)sender;
            grid.BindColumns();
        }

        private void BindColumns()
        {
            foreach (var x in this.Columns)
            {
                if (!string.IsNullOrEmpty(x.SortMemberPath))
                {
                    if (ColumnNames.Contains(x.SortMemberPath as string))
                    {
                        x.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        x.Visibility = Visibility.Collapsed;
                    }
                }
            }          
        }
    }
}
